<script setup lang="ts">
import {getEmailCount, saveEmails} from "~/api/emailApi.ts";
  import {RegisterRate} from "~/api/registerApi.ts";

  const apiPrefix = 'registerRate'

  const { state, query } = useTable({
    apiPrefix,
    searchColumn: [],
    afterQuery: (res) => {
      let emailTypeSet = new Set<string>()
      res.list.forEach((item:any) => {
        item.id = item.linkCode
        emailTypeSet.add(item.useEmailType)
      })
      emailsTypes = Array.from(emailTypeSet)
      initEmailCount()
      return res
    },
    _pagination:{
      column: '',
      pageSize: 999,
      pageSizeOptions: ['999']
    },
  })
  const {formState,message,openForm,handleEdit,handleDelete,handleOk,handleCancel} = useForm({
    apiPrefix,query
  })
  function handleAdd(){
    openForm({controlType: 'register'} as RegisterRate)
  }
  const columns = shallowRef([
    {
      title: '链接码',
      dataIndex: 'linkCode',
    },
    {
      title: '每日注册数',
      dataIndex: 'count',
    },
    {
      title: '尝试注册数',
      dataIndex: 'runCount'
    },
    {
      title: '成功注册数',
      dataIndex: 'successCount'
    },
    {
      title: '邮箱类型',
      dataIndex: 'useEmailType',
    },
    {
      title: '控制类型',
      dataIndex: 'controlType'
    },
    {
      title: '操作',
      dataIndex: 'action'
    }
  ])
  let emailsTypes = [] as string[]
  let mailCount = ref({})
  function initEmailCount(){
    getEmailCount().then(res=>{
      console.log(res.data)
      mailCount.value = res.data
    })
  }
  function unescapeChars(str) {
    return str.replace(/\\t/g, '\t')
        .replace(/\\n/g, '\n')
    // 可以添加其他需要转义的字符
  }

  const showAddEmail = ref(false)
  const emailFormState = reactive<{unHandleEmails:string,splitStr:string,type:string}>({
    unHandleEmails:"",
    splitStr:"",
    type: ""
  })
  function submit(){
    if(!emailFormState.unHandleEmails || !emailFormState.splitStr){
      message.error('请输入邮箱和分隔符')
      return
    }
    let lines = emailFormState.unHandleEmails.split("\n")
    let emails = [] as any[]
    lines.forEach(function(line){
      let emailInfo = line.split(unescapeChars(emailFormState.splitStr))
      if(emailInfo.length >= 2){
        emails.push({
          email: emailInfo[0],
          password: emailInfo[1],
          type: emailFormState.type
        })
      }
    })
    if (emails.length > 0){
      saveEmails(emails).then(res=>{
        if (res.status == 200){
          message.success('上传成功')
          showAddEmail.value = false
        }else{
          message.error('上传失败')
        }
      })
    }
  }
</script>

<template>
      <a-card>
        <template #extra>
          <a-space size="large">
            <div v-for="item in Object.keys(mailCount)">
              <span style="color: red;font-size: large">
                {{item}}
              </span>
              <span style="font-size: large">
              :{{mailCount[item]}}
              </span>
            </div>
            <a-button type="primary" @click="handleAdd">
              新增
            </a-button>
            <a-button type="primary" style="background-color: #41cd21" @click="()=>showAddEmail = true">
              导入邮箱
            </a-button>
          </a-space>
        </template>
        <a-table
            row-key="id" :row-selection="state.rowSelections" :loading="state.loading" :columns="columns"
            :data-source="state.dataSource" :pagination="state.pagination"
        >
          <template #bodyCell="scope">
            <template v-if="scope?.column?.dataIndex === 'action'">
              <div flex gap-2>
                <a-button type="link" @click="handleEdit(scope?.record as RegisterRate)">
                  编辑
                </a-button>
                <a-popconfirm
                    title="确定删除该条数据？" ok-text="确定" cancel-text="取消"
                    @confirm="handleDelete(scope?.record as RegisterRate)"
                >
                  <a-button type="link">
                    删除
                  </a-button>
                </a-popconfirm>
              </div>
            </template>
          </template>
        </a-table>
      </a-card>
      <a-modal v-model:visible="formState.formVisible" :title="formState.isUpdate?'编辑':'新增'" @ok="handleOk" @cancel="handleCancel">
        <a-form ref="formRef" :model="formState.formData" class="w-full" :label-col="{ style: { width: '150px' } }" :wrapper-col="{ span: 12 }">
          <a-form-item name="linkCode" label="链接码" :rules="[{ required: true, message: '请输入链接码' }]">
            <a-input-number v-model:value="formState.formData.linkCode" :min="5" :max="99999" placeholder="请输入链接码" />
          </a-form-item>
          <a-form-item name="count" label="注册数" :rules="[{ required: true, message: '请输入注册数' }]">
            <a-input-number v-model:value="formState.formData.count" :min="0" :max="9999"  placeholder="请输入注册数" />
          </a-form-item>
          <a-form-item name="useEmailType" label="邮箱类型">
              <a-input v-model:value="formState.formData.useEmailType" :maxlength="20" placeholder="请输入邮箱类型" />
          </a-form-item>
          <a-form-item name="controlType" label="控制类型" :rules="[{ required: true, message: '请输入控制类型' }]">
            <a-input v-model:value="formState.formData.controlType" :maxlength="20" placeholder="请输入控制类型" />
          </a-form-item>
        </a-form>
      </a-modal>
      <a-modal v-model:visible="showAddEmail" title="导入邮箱" @ok="submit">
        <a-form ref="eFormRef" :model="emailFormState" class="w-full" :label-col="{ style: { width: '100px' } }" :wrapper-col="{ span: 24 }">

            <a-form-item name="type" label="类型" :rules="[{ required: true, message: '请输入类型' }]">
<!--              <a-input v-model:value="emailFormState.type" :maxlength="50" placeholder="请输入类型" />-->
              <a-select
                  ref="select"
                  v-model:value="emailFormState.type"
                  style="width: 160px"
              >
                <a-select-option v-for="item in emailsTypes" :value="item">{{item}}</a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item name="splitStr" label="分隔符" :rules="[{ required: true, message: '请输入分隔符' }]">
              <a-input v-model:value="emailFormState.splitStr" :maxlength="50" placeholder="请输入分隔符" />
            </a-form-item>
            <a-form-item name="emails" label="邮箱" >
              <a-textarea
                  v-model:value="emailFormState.unHandleEmails"
                  placeholder="请输入邮箱"
                  :auto-size="{ minRows: 5, maxRows: 5 }"
              />
            </a-form-item>
        </a-form>
      </a-modal>
</template>

<style scoped lang="less">

</style>